package com.hidataplus.hadoop.tezui;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class LoginFilter
 */
//@WebFilter(filterName = "LoginFilter", urlPatterns = "/*")
public class LoginFilter implements Filter {

    public static Logger logger = LoggerFactory.getLogger(LoginFilter.class);

    /**
     * 需要排除的页面
     */
    private String excludedPages;
    private String[] excludedPageArray = {"/login.jsp",  "/LoginServlet.do","/LogoutServlet.do"};

    /**
     * Default constructor.
     */
    public LoginFilter() {
        // TODO Auto-generated constructor stub
    }


    /**
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain)
            throws IOException, ServletException {
        // TODO Auto-generated method stub
        // place your code here

        // pass the request along the filter chain
        //chain.doFilter(request, response);
        HttpServletRequest request = (HttpServletRequest) arg0;
        HttpServletResponse response = (HttpServletResponse) arg1;
        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("user");
        logger.info("user:" + user);
        String uri = request.getRequestURI();
        logger.info("uri:" + uri);

        boolean isExcludedPage = false;
        for (
                String page : excludedPageArray) {// 判断是否在过滤 url 之外
            if (request.getServletPath().equals(page)) {
                isExcludedPage = true;
                break;
            }
        }

        if (isExcludedPage) {// 在过滤 url 之外
            chain.doFilter(arg0, arg1);
        }else if (user == null ) {
//            //没有登录
//            PrintWriter out = response.getWriter();
//            out.print("<script language='javascript'>alert('Please login first!');window.location.href='/login.jsp';</script>");
//            out.flush();
//            out.close();

            response.sendRedirect( request.getContextPath()+ "/login.jsp");

            //arg2.doFilter(arg0, arg1);
        } else {
            logger.info("continue do filter");
            chain.doFilter(arg0, arg1);
        }
    }

    @Override
    public void destroy() {

    }

    /**
     * @see Filter#init(FilterConfig)
     */
    public void init(FilterConfig fConfig) throws ServletException {
        // TODO Auto-generated method stub
    }

}
